package com.bubblegumproject.ogo.component.injection;

import com.bubblegumproject.ogo.action.Context;
import org.apache.log4j.Logger;

import java.util.Collection;

/**
 * DependencyInjector that attempts to inject all dependencies by searching the {@link Context} for the best
 * match.
 *
 * @author Azubuko Obele (buko.obele@gmail.com)
 */
public class ContextDependencyInjector extends AbstractDependencyInjector {

    private static final Logger log = Logger.getLogger(ContextDependencyInjector.class);

    public void inject(Collection<Injector> injectors, Context context) {
        for (Injector injector : injectors) {
            Object result;

            if (injector.isNamed()) {
                result = findByName(injector.getName(), context);
            } else {
                result = findByClass(injector.getTargetType(), context);
            }

            if (result != null) {
                injector.inject(result);
                log.debug(this + " injected " + result + " to " + injector);
            }
        }
    }

    protected Object findByName(String name, Context context) {
        return context.get(name);
    }

    private Object findByClass(Class clazz, Context context) {
        Context targetContext = context;
        while (targetContext != null) {
            for (Object o : targetContext.getData().values()) {
                if (clazz.isInstance(o)) return o;
            }

            targetContext = targetContext.getParent();
        }
        return null;
    }
}
